package com.i1510.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.*;

public class JstSignUtil {
    private JstSignUtil() {}

    public static String getSign(String app_secret, Map<String, String> params) {
        try {
            String sortedStr = getSortedParamStr(params);
            String paraStr = app_secret + sortedStr;

            return createSign(paraStr);
        } catch (UnsupportedEncodingException e) {
            System.out.println("getSign UnsupportedEncodingException： "+e);
        }

        return "";
    }

    /**
     * 构造自然排序请求参数
     *
     * @param params 请求
     * @return 字符串
     */
    private static String getSortedParamStr(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> sortedParams = new TreeSet<>(params.keySet());

        StringBuilder strB = new StringBuilder();
        // 排除sign和空值参数
        for (String key : sortedParams) {
            if ("sign".equalsIgnoreCase(key)) {
                continue;
            }

            String value = params.get(key);

            if (!StringUtils.isEmpty(value)) {
                strB.append(key).append(value);
            }
        }
        return strB.toString();
    }

    /**
     * 生成新sign
     *
     * @param str 字符串
     * @return String
     */
    private static String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            System.out.println("create sign was failed： "+e);
            return null;
        }
    }

    public static void main1(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key","97989cda6d0d4ad3b72cd3ca5f264667");
        params.put("access_token","90aafb5ed7b64b41b85ba6b9aa820131");
        params.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version","2");
        params.put("charset","utf-8");
        params.put("biz","{\"page_index\":\"1\",\"page_size\":\"100\",\"nicks\":[\"老板\"]}\n");
        System.out.println(getSign("1cccc2e208954df4aed5a0bc78fd7262",params));
        String dateStr = "0001/1/1 0:00:00";
        Date date = DateUtil.parse(dateStr);
        System.out.println("--"+DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
        System.out.println(DateUtil.today()+"--"+NumberUtil.toBigDecimal("32.09"));
        JSONObject rtnObj = JSONObject.parseObject("{\"msg\":\"执行成功\",\"code\":0,\"data\":{\"datas\":[{\"msg\":\"成功\",\"issuccess\":true,\"so_id\":\"sn172646820221128105752\",\"o_id\":1824,\"split_id\":null}],\"requestId\":null}}");

        JSONArray datas = rtnObj.getJSONObject("data").getJSONArray("datas");
        System.out.println(datas.getJSONObject(0).get("o_id"));
        StringBuffer sb = new StringBuffer();
        sb.append("12X31X23");
        System.out.println("X:"+sb.indexOf("X"));


    }

    //token过期重新获取
//    "access_token": "a58dbba593284654882664be41bacbea",
//            "expires_in": 2592299,
//            "refresh_token": "27def5991c90409fb2874bcad70ea49c",
    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key","97989cda6d0d4ad3b72cd3ca5f264667");
        params.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type","authorization_code");
        params.put("charset","utf-8");
        params.put("code","jst123");
        System.out.println(params);
        System.out.println(getSign("1cccc2e208954df4aed5a0bc78fd7262",params));


    }

    //token更新
    public static void main2(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("app_key","97989cda6d0d4ad3b72cd3ca5f264667");
        params.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        params.put("grant_type","refresh_token");
        params.put("charset","utf-8");
        params.put("refresh_token","48bf557377d441d6ad774c2c23e3d94c");
        params.put("scope","all");
        System.out.println(params);
        System.out.println(getSign("1cccc2e208954df4aed5a0bc78fd7262",params));


    }
}
